<?php
namespace Admin\Controller;
use Think\ControllerEx;
class OrderController extends CommonController {

    public function _initialize(){

        $goodsRes = R('Goods/getGoods',array('0'));
        $this->goodsRes = $goodsRes;
        $this->base_init(null);
    }
     //加载 耗材列表 页面
    public function upGoods(){
        $goodsRes = R('Goods/getGoods',array('1'));
        $orderRes =  $this->isOrder();
        $this->assign('goodsList',$goodsRes);
        
        //没有上报加载 上报页面
        if ($orderRes) {
            //已上报 加载 当月上报 订单信息
            
            $this->assign('order',$orderRes);
            $this->display('isup');
        }else{

            $this->display('upGoods');
        }
    }

    /**
     * 查看 本月是否已入库
     * 已上报 返回  订单号 oid 及订单状态 status
     * 没有上报返回 false
     */
    public function isOrder($uid = '0'){
        if ($uid == '0') {
            $uid = session('admin')['uid'];
        }
        
        $where['uid'] = $uid;
        $where['ym']  = date('Ym',time());
        $orderTab = M('Order');
        $orderRes = $orderTab->where($where)->field('oid,datetime,ym,status,comm')->find();
        //查到订单信息 返回 订单 
        if ($orderRes) {
            $date = $this->viewOrde($orderRes['oid']);
            $orderRes['goodsList'] = $date['goodsList'];
            $orderRes['totalAll'] = $date['totalAll'];
            if(IS_AJAX){
                $this->ajaxReturn($orderRes);
            }else{
                return $orderRes;
            }
        }else{
            //没有查到信息 返回 false 
            if(IS_AJAX){
                $this->ajaxReturn(false);
            }else{
                return false;
            }
        }
    }


    //耗材入库操作
    public function putin(){

        $date = I('post.');   //获取提交 的入库信息
         //删除 入库数为零的 耗材
        for ($i=0; $i < count($date['num']); $i++) { 
            if (!empty($date['num'][$i])) {
                   
                    $goodsUp[] = array('gid'=>$date['gid'][$i],'num'=>$date['num'][$i]);
                } 
        }

        if ($date['oid'] == null ) {
            $oid = $this->createOid($uid,$date['comm']);
        }else{
            $oid = $date['oid'];
            //删除 所有原订单详情
            $this->delOrdetails($oid);
            //修改订单 comm
            $orderTab = M('Order');
            $orderTab->comm = $date['comm'];
            $orderTab->where('oid='.$oid)->save();
        }

        //实例化 订单详情表
        $order_detailsTab = M('Order_details');

        for ($i=0; $i < count($goodsUp); $i++) {
            //获取 耗材最新的信息
            $goodsRes         = R('Goods/getRes',array($goodsUp[$i]['gid']));
            $newDate['oid']   = $oid;
            $newDate['gid']   = $goodsUp[$i]['gid'];
            $newDate['num']   = $goodsUp[$i]['num'];

            $newDate['price'] = $goodsRes['price'];
            $newDate['total'] = $goodsRes['price']*$newDate['num']; //单品总价
            $newDate['ym']    = date('Ym');

            //记录订单详情 
            $odid[] = $order_detailsTab->add($newDate);
            //加库存 goods表 amount字段库存数增加   type= 1增加库存
            $amountDate = array($newDate['gid'],$newDate['num'],'1');
            R('Goods/updateAmount',$amountDate);
        }
        //$this->redirect('Admin/Goods/index', 5, '页面跳转中...');
        $this->success('入库成功','upGoods','2');
    }

    //删除旧订单
    private function delOrdetails($oid){
        //实例化 订单详情表
        $order_detailsTab = M('Order_details');
        $where['oid'] = $oid;
        $orderRes = $order_detailsTab->where($where)->delete();
        //echo $order_detailsTab->getLastsql();die;
        if ($orderRes) {
            return true;
        }else{
            return false;
        }
    }


    //生成新订单 oid
    private function createOid(){
        $user  = session('admin');
        $orderDate['uid']        = $user['uid'];

        $orderDate['branchname'] = $user['branchname'];
        $orderDate['type']       = '1';  //类型1 为入库
        $orderDate['ym']         = date('Ym');
        $orderDate['datetime']   = time();  

        //实例化 订单表
        $orderTab = M('Order');
        //生成订单
        $orderRes = $orderTab->add($orderDate);
        if ($orderRes) {
            return $orderRes;   //返回 最新订单 oid
        }else{
            $this->error('订单生成失败');
        }
    }

    //查看月报表
    public function monthly(){
        $data = I('post.');
        if(empty($data)) {
            $ym = date('Ym',time());
        }else{
            $ym = $data['ym']; 
        }
        
        //上一个月
        if (isset($data['up'])) {
            $strYm = $ym.'01'.'-1 month';
            $ym = date('Ym',strtotime($strYm));
        }

        //下一个月 
        if (isset($data['down'])) {
            $strYm = $ym.'01'.'+ 1 month';
            if (strtotime($strYm) > strtotime(date('Ym'))) {

                echo "<h2 style='color:red'>已为最后一个月</h2> 数据";
                $strYm = $ym.'01';
            }
           
            $ym = date('Ym',strtotime($strYm));
        }
        $year   = substr($ym,0,4);
        $month  = substr($ym,4,2);
        $ymNew  = array('yy'=>$year,'mm'=>$month,'ym'=>$ym);

        $orderTab = M('Order');
        $where['user.role'] = 0;
        $userTab = M('User');
        $orderRes = $userTab->alias('user')
                            ->where($where)
                            ->join('LEFT JOIN pl_order ord ON ord.uid = user.uid AND ord.ym ='.$ym .' AND ord.type = 0')
                            ->field('user.uid,user.branchname,ord.oid,ord.status,ord.comm')
                            ->order('user.uid asc')
                            ->select();
                            
        for ($i=0; $i < count($orderRes); $i++) {
            $date = $this->viewOrde($orderRes[$i]['oid']);
            $orderRes[$i]['goodsList'] = $date['goodsList'];
            $orderRes[$i]['totalAll']  = $date['totalAll'];
        }
        $this->assign('orderList',$orderRes);
        //dump($orderRes);//dump($orderRes);
        $this->assign('ym',$ymNew);

        $goodsRes = $this->goodsRes;
        $this->assign('goodsList',$goodsRes);

        $storage = $this->getStorage($ym);  //获取本月入库数
        $this->assign('stroage',$storage);
        
        $this->display('order_monthly');
    }

    //获取 本月 入库数
    private function getStorage($ym){
        $orderTab      = M('Order');
        $where['ym']   = $ym;
        $where['type'] = '1';
        
        $oid = $orderTab->where($where)->getField('oid');
        $orderRes = $this->viewOrde($oid);
        return $orderRes;
    }


    //根据 订单号 查看订单详情 
    private function viewOrde($oid = 0){

        $goodsRes  = $this->goodsRes;
        if ($oid  !== null) {
            $goodsList = R('OrderDet/getOrderlist',array($oid));
        }else{
            $goodsList = array();
        }
        //将订单 所有的 gid 放入 一个新数组
        $gidList = array_keys($goodsList);
        
        //循环商品列表
        for ($g=0; $g < count($goodsRes); $g++) {
            //如果 商品 耗材订单详情表中
            if (in_array($goodsRes[$g]['gid'], $gidList)) {    
                $orderRes['goodsList'][] = $goodsList[$goodsRes[$g]['gid']];
            }else{
                $orderRes['goodsList'][] = array('gid'=>$goodsRes[$g]['gid'],'price'=>'','num'=>'','total'=>'');
            }
        } 
        $goodsList['total'] = array_column($goodsList,'total');
        $orderRes['totalAll'] = array_sum($goodsList['total']);
        return $orderRes;
    }


    //代替上报耗材 
    public function daiUp()
    {   
        if(date('d') >= 21 ){
            echo "<h3 style='color:red'>已过21日不能上报！</h3>";
            $this->monthly();
            die;
        }
        $goodsRes = $this->goodsRes;
        $this->assign('goodsList',$goodsRes);

        $userRes = R('User/getNoreport');
        if ($userRes) {
            $this->assign('userRes',$userRes);
            $this->display();
        }else{
            echo "全部上报";
        }
    }

}